package com.bro.broshopping;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.util.Pair;

/**
 * Helper class to ease use of the local storage
 * @author adwicki
 *
 */
public class LocalStorage {
	// config
	private final static String FILENAME = "localStorage";
	private final static String USER_TAG = "user"; 
	
	
	public static void storeUserData (String username, String password, Activity act) {
		JSONObject obj = new JSONObject();
		try {
			obj.put("username", username);
			obj.put("password", password);
			
			// store string in file
			FileOutputStream fos = act.openFileOutput(FILENAME+USER_TAG, Context.MODE_PRIVATE);
			String out = obj.toString();
			fos.write(out.getBytes());
			fos.close();
		} catch (Exception e) {
			Log.d("JSON", "Error happened while encoding to JSON\n"+e.toString());
			e.printStackTrace();
		}
	}
	
	public static Pair<String, String> getUserData(Activity act){
		try {
			FileInputStream fin = act.openFileInput(FILENAME+USER_TAG);
			byte[] buffer = new byte[1024];
			fin.read(buffer);
			fin.close();
			String jsonStr = new String(buffer);
			// parse json string
			if (!buffer.toString().equals("")){
				JSONObject obj = new JSONObject(jsonStr);
				return new Pair<String,String>(obj.getString("username"), obj.getString("password"));
			} else {
				return null;
			}
			
		} catch (Exception e) {
			Log.d("FileOp", "Error while performing file op\n"+e.toString());
		}
		return null;
	}
}
